package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {

        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);

        //2.添加任务到redis
        if (success) {
            addTaskToRedis(task);
        }


        //3.返回任务id
        return task.getTaskId();
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskToRedis(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //获取未来5分钟的时间点
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);


        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //1 如果任务的执行时间小于等于当前时间  存入list
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            //2 如果任务的执行时间大于当前时间&&小于等于未来5分钟  存入zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {
            //保存任务
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //给task赋值id
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogs.setVersion(1);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务添加失败");
        }
        return flag;

    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {

        boolean flag = false;

        //更新数据库中的任务
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //删除redis中对应的任务数据
        if(task != null){
            removeTaskFromRedis(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 删除redis中对应的任务数据
     * @param task
     */
    private void removeTaskFromRedis(Task task) {

        String key = task.getTaskType()+"_"+task.getPriority();

        //任务的执行时间小于等于当前时间   删除list
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0, JSON.toJSONString(task));
        }else {
            //其他情况 删除zset
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }

    }

    /**
     * 更新任务
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {

        Task task = null;

        try {
            //删除任务数据
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            //返回task
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务更新失败");
        }
        return task;

    }

    /**
     * 拉取任务
     * @param taskType 任务类型
     * @param priority 任务优先级
     * @return
     */
    @Override
    public Task poll(int taskType, int priority) {
        Task task = null;
        try {
            String key = taskType+"_"+priority;

            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
               task = JSON.parseObject(task_json, Task.class);
                //更新数据库中的任务
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务拉取失败");
        }

        return task;
    }

    /**
     * redis的管道流技术  从zset获取符合条件的数据，存入list  删除zset
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            System.out.println("当前时间："+new Date());
            Set<String> futureKesy = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKesy) {//future_50_100

                //topic_50_100
                String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];

                //获取符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if(!tasks.isEmpty()){
                    //同步数据
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    log.info("成功的将"+futureKey+"的数据同步到了"+topicKey);
                }

            }
        }

    }

    /**
     * 从数据库中同步到redis
     */
    @PostConstruct  //spring加载bean的初始化方法
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){

        //清理缓存
        clearCache();

        //获取未来5分钟的时间点
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查询符合条件的数据  小于等于未来5分钟的数据
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        if(!taskinfoList.isEmpty()){
            for (Taskinfo taskinfo : taskinfoList) {

                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //同步到redis
                addTaskToRedis(task);
            }
        }
        log.info("数据库任务已经同步到了redis中");

    }

    /**
     * 清理缓存
     */
    private void clearCache() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");

        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);

    }
}
